package edu.chl.food_store.filter;

import edu.chl.food_store.beans.model.LoginModelBean;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;

/**
 * AdminFilter:
 * Controlls access to administration pages.
 */
@WebFilter(filterName = "AdminFilter", urlPatterns = {"/admin/*"})
public class AdminFilter implements Filter {

    private FilterConfig filterConfig = null;

    public AdminFilter() {
    }

    /**
     * Checks if the current user is a logged in admin. If not the user is denied
     * access to administration pages.
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean stop = false;
        if (request instanceof HttpServletRequest) {
            HttpSession session = ((HttpServletRequest) request).getSession(false);
            if (session != null) {
                LoginModelBean loginStatus = (LoginModelBean) session.getAttribute("loginModelBean");
                if (loginStatus != null && !loginStatus.isAdmin()) {
                    ((HttpServletResponse) response).sendRedirect("/food_store/notAdmin.xhtml");
                    stop = true;
                }
            }
        }
        if (!stop) {
            chain.doFilter(request, response);
        }
    }

    /**
     * Destroy method for this filter 
     */
    @Override
    public void destroy() {
    }

    /**
     * Init method for this filter 
     */
    @Override
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
}
